package com.example.dto;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.security.oauth2.server.authorization.settings.OAuth2TokenFormat;

import java.io.IOException;
import java.time.Duration;

public class TokenSettingsDeserializer extends JsonDeserializer<TokenSettingsDTO> {

    @Override
    public TokenSettingsDTO deserialize(JsonParser p, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        // 读取 JSON 节点
        JsonNode node = p.getCodec().readTree(p);

        // 创建 DTO 对象
        TokenSettingsDTO dto = new TokenSettingsDTO();

        // 解析字段
        dto.setReuseRefreshTokens(node.get("settings.token.reuse-refresh-tokens").asBoolean());

        // 解析 id-token-signature-algorithm
        JsonNode signatureAlgorithmNode = node.get("settings.token.id-token-signature-algorithm");
        String signatureAlgorithmValue = signatureAlgorithmNode.get(1).asText();
        dto.setIdTokenSignatureAlgorithm(SignatureAlgorithm.from(signatureAlgorithmValue));

        // 解析 access-token-time-to-live
        JsonNode accessTokenTimeToLiveNode = node.get("settings.token.access-token-time-to-live");
        long accessTokenSeconds = (long) accessTokenTimeToLiveNode.get(1).asDouble();
        dto.setAccessTokenTimeToLive(Duration.ofSeconds(accessTokenSeconds));

        // 解析 access-token-format
        JsonNode accessTokenFormatNode = node.get("settings.token.access-token-format");
        String accessTokenFormatValue = accessTokenFormatNode.get("value").asText();
        dto.setAccessTokenFormat(new OAuth2TokenFormat(accessTokenFormatValue));

        // 解析 refresh-token-time-to-live
        JsonNode refreshTokenTimeToLiveNode = node.get("settings.token.refresh-token-time-to-live");
        long refreshTokenSeconds = (long) refreshTokenTimeToLiveNode.get(1).asDouble();
        dto.setRefreshTokenTimeToLive(Duration.ofSeconds(refreshTokenSeconds));

        // 解析 authorization-code-time-to-live
        JsonNode authCodeTimeToLiveNode = node.get("settings.token.authorization-code-time-to-live");
        long authCodeSeconds = (long) authCodeTimeToLiveNode.get(1).asDouble();
        dto.setAuthorizationCodeTimeToLive(Duration.ofSeconds(authCodeSeconds));

        // 解析 device-code-time-to-live
        JsonNode deviceCodeTimeToLiveNode = node.get("settings.token.device-code-time-to-live");
        long deviceCodeSeconds = (long) deviceCodeTimeToLiveNode.get(1).asDouble();
        dto.setDeviceCodeTimeToLive(Duration.ofSeconds(deviceCodeSeconds));

        return dto;
    }
}